package com.lovol.surfaceviewdemo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by ypk on 2023/4/11
 * 移动的小球
 */
public class BallView extends SurfaceView implements Runnable {

    // 小球的位置和速度
    private float x = 100;
    private float y = 100;
    private float vx = 5;
    private float vy = 5;


    // 线程对象
    private Thread thread;
    // SurfaceHolder对象
    private SurfaceHolder holder;
    // 游戏是否在运行
    private volatile boolean running = false;

    public BallView(Context context) {
        super(context);
        // 获取SurfaceHolder对象
        holder = getHolder();
    }

    // 启动游戏循环线程
    public void resume() {
        running = true;
        thread = new Thread(this);
        thread.start();
    }

    // 暂停游戏循环线程
    public void pause() {
        running = false;
        while (true) {
            try {
                thread.join();
                break;
            } catch (InterruptedException e) {
                // 重试
            }
        }
        thread = null;
    }

    // 游戏循环
    @Override
    public void run() {
        while (running) {
            if (holder.getSurface().isValid()) {
                // 获取Canvas对象并进行绘制
                Canvas canvas = holder.lockCanvas();
                // 绘制背景
                canvas.drawColor(Color.BLACK);
                // 绘制小球
                Paint paint = new Paint();
                paint.setColor(Color.RED);
                canvas.drawCircle(x, y, 50, paint);
                // 更新小球位置
                x += vx;
                y += vy;
                if (x < 50 || x > getWidth() - 50) {
                    vx = -vx;
                }
                if (y < 50 || y > getHeight() - 50) {
                    vy = -vy;
                }
                // 解锁Canvas对象并提交绘制结果
                holder.unlockCanvasAndPost(canvas);
            }
        }
    }
}
